package com.service.tools;

import java.io.IOException;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * Json 与 Object 互相转换
 * 
 * @author lj Created on 2015年5月20日
 */
public class JsonConvert {

	private ObjectMapper objectMapper = null;

	private void init() {
		if (objectMapper == null) {
			objectMapper = new ObjectMapper();
		}
	}

	private void destory() {
		objectMapper = null;
		System.gc();
	}
	
	/**
	 * JavaBean、Array、Collection、Map --> Json
	 * @param obj
	 * @return String Json
	 */
	public String object2Json(Object obj) {
		String json = null;
		try {
			init();
			json = objectMapper.writeValueAsString(obj);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		} finally {
			destory();
		}
		return json == null ? "" : json;
	}
	
	/**
	 * Json --> JavaBean、Array、Collection、Map
	 * @param json
	 * @param clazz 对象类
	 * @return Object
	 */
	public Object json2Object(String json, Class<?> clazz) {
		Object obj = null;
		try {
			init();
			obj = objectMapper.readValue(json, clazz);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			destory();
		}
		return obj;
	}

}
